package cn.tedu.homework.work1;

import cn.tedu.jbdc.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCReg2 {
    public static void main(String[] args) {
        try (Connection connection = cn.tedu.jbdc.DBUtil.getConnection()) {
            while (true) {
                Scanner scanner = new Scanner(System.in);
                System.out.println("请输入用户名:");
                String username = scanner.nextLine();
                if (selectAll(username)) {
                    System.out.println("用户名被占用");
                    continue;
                }
                System.out.println("请输入密码:");
                String password = scanner.nextLine();
                System.out.println("请输入昵称:");
                String nickname = scanner.nextLine();
                System.out.println("请输入年龄:");
                int age = scanner.nextInt();

                String sql = "insert into userinfo(username,password,nickname,age) values (?,?,?,?)";

                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setString(1, username);
                ps.setString(2, password);
                ps.setString(3, nickname);
                ps.setInt(4, age);

                int i = ps.executeUpdate();
                if (i > 0) {
                    System.out.println("注册成功");
                    break;
                }

            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }

    public static boolean selectAll(String username) {
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "select id from userinfo where username=?";

            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, username);

            ResultSet resultSet = ps.executeQuery();
            if (resultSet.next()) {
                return true;
            }
            return false;

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
